<template>
  <div>
    <div class="gva-table-box">
      <div class="gva-btn-list">
        <el-button
          v-if="routeName == 'burial'"
          type="primary"
          icon="plus"
          @click="openDialog"
        >新增</el-button>
      </div>
      <el-table
        ref="multipleTable"
        style="width: 100%"
        tooltip-effect="dark"
        :data="tableData"
        border
        row-key="ID"
      >
        <el-table-column
          align="left"
          label="事件名"
          prop="name"
          width="400"
        />
        <el-table-column
          align="left"
          label="标识"
          prop="flag"
          width="300"
        />
        <!-- <el-table-column
          align="left"
          label="是否关键行为"
          width="300"
        >
          <template #default="scope">
            <el-icon v-if="scope.row.is_key>0"><Select /></el-icon>
          </template>
        </el-table-column> -->
        <el-table-column
          align="left"
          label="操作"
          fixed="right"
          min-width="240"
        >
          <template #default="scope">
            <el-button
              type="primary"
              link
              class="table-button"
              @click="getDetails(scope.row)"
            >
              <el-icon style="margin-right: 5px"><InfoFilled /></el-icon>
              数据详情
            </el-button>
            <template v-if="routeName == 'burial'">
              <el-button
                type="primary"
                link
                icon="edit"
                class="table-button"
                @click="updateQmBurialFunc(scope.row)"
              >变更</el-button>
              <template v-if="['showAD','ViewOverAD','active','duration','itemEvent','schedule'].includes(scope.row.flag)">
                <el-button
                  disabled
                  link
                  icon="WarnTriangleFilled"
                >默认事件</el-button>
              </template>
              <template v-else>
                <el-button
                  type="primary"
                  link
                  icon="delete"
                  @click="deleteRow(scope.row)"
                >删除</el-button>
              </template>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination
          layout="total, sizes, prev, pager, next, jumper"
          :current-page="page"
          :page-size="pageSize"
          :page-sizes="[10, 30, 50, 100]"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>
    <el-dialog
      v-model="dialogFormVisible"
      :before-close="closeDialog"
      :title="type==='create'?'添加':'修改'"
      destroy-on-close
    >
      <el-scrollbar height="500px">
        <el-form
          ref="elFormRef"
          :model="formData"
          label-position="right"
          :rules="rule"
          label-width="100px"
        >
          <el-form-item
            label="事件名:"
            prop="name"
          >
            <el-input
              v-model="formData.name"
              :clearable="true"
              placeholder="请输入事件名"
            />
          </el-form-item>
          <el-form-item
            label="事件标识:"
            prop="flag"
          >
            <el-input
              v-model="formData.flag"
              :disabled="type==='update' ? true : false"
              :clearable="true"
              placeholder="请输入事件标识"
            />
          </el-form-item>
          <!-- <el-form-item
            label=""
            prop="is_key"
          >

            <el-radio-group v-model.number="formData.is_key">
              <el-radio-button
                label="非关键行为"
                value="-1"
              />
              <el-radio-button
                label="关键行为"
                value="1"
              />
            </el-radio-group>
          </el-form-item> -->
        </el-form>
      </el-scrollbar>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button
            type="primary"
            @click="enterDialog"
          >确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      v-model="detailShow"
      style="width: 800px"
      lock-scroll
      :before-close="closeDetailShow"
      title="查看详情"
      destroy-on-close
    >
      <el-scrollbar height="550px">
        <el-descriptions
          column="1"
          border
        >
          <el-descriptions-item label="事件命">
            {{ formData.name }}
          </el-descriptions-item>
          <el-descriptions-item label="事件标识">
            {{ formData.flag }}
          </el-descriptions-item>
          <el-descriptions-item label="事件标识">
            {{ formData.flag }}
          </el-descriptions-item>
        </el-descriptions>
      </el-scrollbar>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  createQmBurial,
  deleteQmBurial,
  updateQmBurial,
  findQmBurial,
  getQmBurialList
} from '@/api/qmBurial'
import {
  getQmBurialDataList
} from '@/api/qmBurialData'
// 全量引入格式化工具 请按需保留
import { getDictFunc, formatDate, formatBoolean, filterDict, ReturnArrImg, onDownloadFile } from '@/utils/format'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, reactive } from 'vue'
import { useRouter, useRoute } from 'vue-router'
defineOptions({
  name: 'QmBurial'
})
const router = useRouter()
const route = useRoute()

// 自动化生成的字典（可能为空）以及字段
const formData = ref({
  name: '',
  flag: '',
  is_key: -1
})

// 验证规则
const rule = reactive({
  name: [{
    required: true,
    message: '',
    trigger: ['input', 'blur'],
  },
  {
    whitespace: true,
    message: '不能只输入空格',
    trigger: ['input', 'blur'],
  }
  ],
  flag: [{
    required: true,
    message: '',
    trigger: ['input', 'blur'],
  },
  {
    whitespace: true,
    message: '不能只输入空格',
    trigger: ['input', 'blur'],
  }
  ],
})

const elFormRef = ref()
const elSearchFormRef = ref()

// =========== 表格控制部分 ===========
const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const tableData = ref([])
const searchInfo = ref({})
const routeName = ref('')
routeName.value = route.name
// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}

// 修改页面容量
const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}

// 查询
const getTableData = async() => {
  const table = await getQmBurialList({ page: page.value, pageSize: pageSize.value, ...searchInfo.value })
  if (table.code === 0) {
    tableData.value = []
    table.data.list.forEach(item => {
      tableData.value.push(item)
    })

    // tableData.value = table.data.list
    total.value = table.data.total
    page.value = table.data.page
    pageSize.value = table.data.pageSize
  }
}

getTableData()

// ============== 表格控制部分结束 ===============

// 获取需要的字典 可能为空 按需保留
const setOptions = async() => {
}

// 获取需要的字典 可能为空 按需保留
setOptions()

// // 多选数据
// const multipleSelection = ref([])
// // 多选
// const handleSelectionChange = (val) => {
//   multipleSelection.value = val
// }

// 删除行
const deleteRow = (row) => {
  ElMessageBox.confirm('确定要删除吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteQmBurialFunc(row)
  })
}

// 批量删除控制标记
const deleteVisible = ref(false)

// 行为控制标记（弹窗内部需要增还是改）
const type = ref('')

// 更新行
const updateQmBurialFunc = async(row) => {
  const res = await findQmBurial({ ID: row.id })
  type.value = 'update'
  if (res.code === 0) {
    formData.value = res.data.burial
    dialogFormVisible.value = true
  }
}

// 删除行
const deleteQmBurialFunc = async(row) => {
  const res = await deleteQmBurial({ ID: row.id })
  if (res.code === 0) {
    ElMessage({
      type: 'success',
      message: '删除成功'
    })
    if (tableData.value.length === 1 && page.value > 1) {
      page.value--
    }
    getTableData()
  }
}

// 弹窗控制标记
const dialogFormVisible = ref(false)

// 查看详情控制标记
const detailShow = ref(false)

// 打开详情弹窗
const openDetailShow = () => {
  detailShow.value = true
}

// 打开详情
const getDetails = async(row) => {
  router.push({ name: 'burialData', query: { id: row.id, flag: row.flag }})
}

// 关闭详情弹窗
const closeDetailShow = () => {
  detailShow.value = false
  formData.value = {
    name: '',
    flag: '',
    is_key: -1
  }
}

// 打开弹窗
const openDialog = () => {
  type.value = 'create'
  dialogFormVisible.value = true
}

// 关闭弹窗
const closeDialog = () => {
  dialogFormVisible.value = false
  formData.value = {
    name: '',
    flag: '',
    is_key: -1
  }
}
// 弹窗确定
const enterDialog = async() => {
  elFormRef.value?.validate(async(valid) => {
    if (!valid) return
    let res
    switch (type.value) {
      case 'create':
        res = await createQmBurial(formData.value)
        break
      case 'update':
        res = await updateQmBurial(formData.value)
        break
      default:
        res = await createQmBurial(formData.value)
        break
    }
    if (res.code === 0) {
      ElMessage({
        type: 'success',
        message: '创建/更改成功'
      })
      closeDialog()
      getTableData()
    }
  })
}

</script>

<style>

</style>
